//
//  PersonalMineViewController.m
//  Btpin
//
//  Created by Vic on 2019/3/12.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "PersonalMineViewController.h"
#import "AppDelegate.h"
#import "MineCell.h"
#import "MineHeaderView.h"
#import "MineBaseInfoViewController.h"
#import "PMineResumeViewController.h"
#import "PMineResumeDeliverViewController.h"
#import "PMineReexamineInviteViewController.h"
#import "PMineCollectViewController.h"
#import "PMineStatusViewController.h"
#import "PMineBusinessCardViewController.h"
#import "PMineInviteFriendViewController.h"
#import "PMineCreditEvaluationViewController.h"
#import "PMineCoachViewController.h"
#import "PMineHeadhuntingViewController.h"
#import "PMineWalletViewController.h"
#import "PMinePrivacySettingViewController.h"
#import "PMineAccountSettingViewController.h"
#import "IDSelectViewController.h"
#import "CompanyFirstInfoViewController.h"
#import "PersonalWorkExperienceViewController.h"
#import "CompanySecondInfoViewController.h"
#import "PersonalFirstInfoViewController.h"
#import "PersonalEducationInfoViewController.h"
#import "GeneralWebViewViewController.h"
#import "CompanyInfoViewController.h"
#import "MineWorkerGuideZhuanqianView.h"
#import "PMinePromotionViewController.h"
#import "FeedbackViewController.h"

@interface PersonalMineViewController ()<UITableViewDelegate, UITableViewDataSource, MineHeaderViewDelegate, MineWorkerGuideZhuanqianViewDelegate>
{
    NSMutableArray *itemDataArray;
    UITableView *mineTableView;
    MineWorkerGuideZhuanqianView *guideZhuanqianView;
}
@property (nonatomic, strong) MineHeaderView *tableViewHeaderView;
@end

@implementation PersonalMineViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    __weak __typeof(self)weakSelf = self;
    [DataToolsControl getMyBaseInfoForWorker:^(BOOL requestFlag) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (requestFlag) {
            if (strongSelf.tableViewHeaderView) {
                [strongSelf.tableViewHeaderView setWorkerPartBaseInfo];
            }
        }
    }];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadDataBaseData) name:NotificationForPersonalJobRefresh object:nil];
    
    itemDataArray = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *arr1 = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *arr2 = [NSMutableArray arrayWithCapacity:0];
    NSString *jobTextCoach = UD_GetOForK(isHeadhuntService);
    NSString *jobText = @"帮您找工作更快，更高薪";
    if (jobTextCoach && jobTextCoach.length) {
        if ([jobTextCoach isEqualToString:@"1"]) {
            jobText = @"已开启";
        }
    }
//    [arr1 addObjectsFromArray:@[@[@"p_mine_status", @"求职状态", (UD_GetOForK(isCurrentCn)?UD_GetOForK(isCurrentCn):@"")], @[@"p_mine_businesscard", @"我的名片", @""], @[@"p_mine_invate", @"邀请好友", @"每邀请一位可赚30-110聘豆"], @[@"p_mine_promotion", @"推广赚钱", @"轻松转发职位，赏金赚不停"], @[@"p_mine_credit", @"职场信用评估", (UD_GetOForK(isCreditLevelCn)?UD_GetOForK(isCreditLevelCn):@"")], @[@"p_mine_coach", @"求职教练", @"一对一远程视频"], @[@"p_mine_headhunting", @"猎头服务", jobText]]];
    [arr1 addObjectsFromArray:@[@[@"p_mine_status", @"求职状态", (UD_GetOForK(isCurrentCn)?UD_GetOForK(isCurrentCn):@"")], @[@"p_mine_businesscard", @"我的名片", @""], @[@"p_mine_invate", @"邀请好友", @"每邀请一位可赚30-110聘豆"], @[@"p_mine_credit", @"职场信用评估", (UD_GetOForK(isCreditLevelCn)?UD_GetOForK(isCreditLevelCn):@"")], @[@"p_mine_coach", @"求职教练", @"一对一远程视频"], @[@"p_mine_headhunting", @"猎头服务", jobText]]];
    [arr2 addObjectsFromArray:@[@[@"p_mine_wallet", @"我的钱包", @""], @[@"p_mine_privacy", @"隐私设置", @""], @[@"p_mine_setting", @"账号设置", @""], @[@"p_mine_feedback", @"意见反馈", @""]]];
    [itemDataArray addObject:arr1];
    [itemDataArray addObject:arr2];
    
    [self initUI];
    
    if (!FirstMineWorker) {
        guideZhuanqianView = [[MineWorkerGuideZhuanqianView alloc] initWithTarget:self];
        UD_SetOForK(isYes, isFirstMineWorker);
    }
}
- (void)mineWorkerGuideZhuanqianViewTap {
    [guideZhuanqianView removeFromSuperview];
    guideZhuanqianView = nil;
}
- (void)initUI {
    mineTableView = [UIToolsControl initTableViewWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-HeightOfTabBar) target:self style:UITableViewStyleGrouped];
    mineTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    mineTableView.rowHeight = MineCellHeight;
    mineTableView.separatorInset = UIEdgeInsetsZero;
    mineTableView.backgroundColor = THEMECOLOR_OF_GRAY;
    [self.view addSubview:mineTableView];
    if (@available(iOS 11.0, *)) {
        mineTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (itemDataArray.count) {
        return itemDataArray.count;
    }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (itemDataArray && itemDataArray.count) {
        return [itemDataArray[section] count];
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineCell *cell = [tableView dequeueReusableCellWithIdentifier:isCellID];
    if (!cell) {
        cell = [[MineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:isCellID];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    [cell reloadDataIcon:itemDataArray[indexPath.section][indexPath.row][0] leftText:itemDataArray[indexPath.section][indexPath.row][1] rightText:itemDataArray[indexPath.section][indexPath.row][2] indexPath:indexPath];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section) {
        switch (indexPath.row) {
            case 0: { // 钱包
                PMineWalletViewController *PMWVC = [[PMineWalletViewController alloc] init];
                PMWVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PMWVC animated:YES];
            } break;
            case 1: { // 隐私
                PMinePrivacySettingViewController *PMPSVC = [[PMinePrivacySettingViewController alloc] init];
                PMPSVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PMPSVC animated:YES];
            } break;
            case 2: { // 账号
                PMineAccountSettingViewController *PMASVC = [[PMineAccountSettingViewController alloc] init];
                PMASVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PMASVC animated:YES];
            } break;
            case 3: { // 意见反馈
                FeedbackViewController *FVC = [[FeedbackViewController alloc] init];
                FVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:FVC animated:YES];
            } break;
            default:
                break;
        }
    } else {
        switch (indexPath.row) {
            case 0: { // 求职状态
                PMineStatusViewController *PMSVC = [[PMineStatusViewController alloc] init];
                PMSVC.setback = ^(BOOL setFlag) {
                    if (setFlag) {
                        NSMutableArray *arr = self->itemDataArray[indexPath.section];
                        [arr replaceObjectAtIndex:indexPath.row withObject:@[@"p_mine_status", @"求职状态", (UD_GetOForK(isCurrentCn)?UD_GetOForK(isCurrentCn):@"")]];
                        [self->itemDataArray replaceObjectAtIndex:indexPath.section withObject:arr];
                        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section], nil] withRowAnimation:UITableViewRowAnimationNone];
                    }
                };
                PMSVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PMSVC animated:YES];
            } break;
            case 1: { // 我的名片
                PMineBusinessCardViewController *PMBCVC = [[PMineBusinessCardViewController alloc] init];
                PMBCVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PMBCVC animated:YES];
            } break;
            case 2: { // 邀请好友
                GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
                GWVC.showType = GeneralWebViewTypeOfInviteFriend;
                GWVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:GWVC animated:YES];
            } break;
//            case 3: { // 推广赚钱
//                PMinePromotionViewController *PMPVC = [[PMinePromotionViewController alloc] init];
//                PMPVC.hidesBottomBarWhenPushed = YES;
//                [self.navigationController pushViewController:PMPVC animated:YES];
//            } break;
            case 3: { // 职场信用评估
                PMineCreditEvaluationViewController *PMCEVC = [[PMineCreditEvaluationViewController alloc] init];
                PMCEVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PMCEVC animated:YES];
            } break;
            case 4: { // 求职教练
                GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
                GWVC.showType = GeneralWebViewTypeOfCoach;
                GWVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:GWVC animated:YES];
            } break;
            case 5: { // 猎头服务(H5)
                GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
                GWVC.showType = GeneralWebViewTypeOfHeadhunting;
                GWVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:GWVC animated:YES];
            } break;
            default:
                break;
        }
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section) {
        return [UIToolsControl initViewWithFrame:CGRectMake(0, 0, WIDTH, 10*Scale) backgroundColor:THEMECOLOR_OF_GRAY];
    } else {
        return self.tableViewHeaderView;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section) {
        return 10*Scale;
    }
    return 235*Scale+((isiPhoneX||isiPhoneXr||isiPhoneXsMax)?ScalePS(20):0);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.00001;
}

- (void)mineHeaderViewTap:(MineHeaderViewTapType)type {
    switch (type) {
        case MineHeaderViewTapTypeOfRoleSwitch: {
            NSLog(@"切换角色");
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
            dic = [UIToolsControl getPublicParameter];
            [dic setObject:@"1" forKey:@"user_role"];
            [BaseNetManager requestWithMethod:POST path:Change_Role_URL params:dic successBlock:^(NSDictionary *responseObject) {
                if ([responseObject[@"code"] integerValue] == 2000) {
                    UD_SetOForK(@"1", isUserRole);
                    
                    NSDictionary *data = responseObject[@"data"];
                    if (data[@"user_guide"] && [data[@"user_guide"] length] && ([data[@"user_guide"] isEqualToString:@"choose_role"])) { // 用户还没选角色 （选择用户角色）
                        IDSelectViewController *IDSVC = [[IDSelectViewController alloc] init];
                        IDSVC.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:IDSVC animated:NO];
                    } else {
                        if ([data[@"user_guide"] isEqualToString:@"company_add_job"]) { // 添加工作 
                            [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                                [SharedApp showViewController:TabBarTypeOfCompany];
                                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                                tabBarController.selectedIndex = 1;
                            }];
                        } else if ([data[@"user_guide"] isEqualToString:@"company_create"]) { // 招聘者下面没有企业的话就会引导创建
                            CompanyFirstInfoViewController *IDSVC = [[CompanyFirstInfoViewController alloc] init];
                            IDSVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:IDSVC animated:NO];
                        } else if ([data[@"user_guide"] isEqualToString:@"company_info"]) { // 填写企业信息
                            CompanySecondInfoViewController *IDSVC = [[CompanySecondInfoViewController alloc] init];
                            IDSVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:IDSVC animated:NO];
                        } else if ([data[@"user_guide"] isEqualToString:@"company_audit"]) { // 企业未认证
                            SVPHUDShow;
                            [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                                SVPHUDDismiss;
                                [SharedApp showViewController:TabBarTypeOfCompany];
                                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                                tabBarController.selectedIndex = tabBarController.viewControllers.count-1;
                                RootNavigationController *navigationController = (RootNavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                                
                                CompanyInfoViewController *CIVC = [[CompanyInfoViewController alloc] init];
                                CIVC.hidesBottomBarWhenPushed = YES;
                                [navigationController pushViewController:CIVC animated:YES];
                            }];
                        } else if (([data[@"user_guide"] isEqualToString:@"resume_create"])) { // 创建简历页
                            PersonalFirstInfoViewController *PMRVC = [[PersonalFirstInfoViewController alloc] init];
                            PMRVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:PMRVC animated:NO];
                        } else if ([data[@"user_guide"] isEqualToString:@"resume_edu"]) { // 完善简历中教育经历
                            if (data[@"is_graduate"] && ([data[@"is_graduate"] integerValue] == 0)) {
                                [DataToolsControl sharedManager].idType = IDTypeOfWorker;
                            } else {
                                [DataToolsControl sharedManager].idType = IDTypeOfFreshGraduate;
                            }
                            
                            PersonalEducationInfoViewController *PMRVC = [[PersonalEducationInfoViewController alloc] init];
                            PMRVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:PMRVC animated:NO];
                        } else if ([data[@"user_guide"] isEqualToString:@"resume_work"]) { // 完善简历中工作经历
                            PersonalWorkExperienceViewController *PMRVC = [[PersonalWorkExperienceViewController alloc] init];
                            PMRVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:PMRVC animated:NO];
                        } else {
                            SVPHUDShow;
                            [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                                SVPHUDDismiss;
                                [SharedApp showViewController:TabBarTypeOfCompany];
                                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                                tabBarController.selectedIndex = tabBarController.viewControllers.count-1;
                            }];
                        }
                    }
                } else {
                    SVPHUDError(responseObject[@"msg"]);
                }
            } failurBlock:^(NSError *error) {
                SVPHUDError(NetErrorAlertText);
            }];
        } break;
        case MineHeaderViewTapTypeOfEditInfo: {
            NSLog(@"编辑信息");
            MineBaseInfoViewController *MBIVC = [[MineBaseInfoViewController alloc] init];
            __weak __typeof(self)weakSelf = self;
            MBIVC.headerImg = ^(NSString *headerImgUrl) {
                __strong __typeof(weakSelf)strongSelf = weakSelf;
                if (headerImgUrl && headerImgUrl.length) {
                    strongSelf.tableViewHeaderView.headerImgUrl = headerImgUrl;
                }
            };
            MBIVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:MBIVC animated:YES];
        } break;
        case MineHeaderViewTapTypeOfResume: {
            NSLog(@"我的简历");
            PMineResumeViewController *PMRVC = [[PMineResumeViewController alloc] init];
            PMRVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRVC animated:YES];
        } break;
        case MineHeaderViewTapTypeOfDeliver: {
            NSLog(@"我的投递");
            PMineResumeDeliverViewController *PMRDVC = [[PMineResumeDeliverViewController alloc] init];
            PMRDVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRDVC animated:YES];
        } break;
        case MineHeaderViewTapTypeOfInvate: {
            NSLog(@"复试邀请");
            PMineReexamineInviteViewController *PMRIVC = [[PMineReexamineInviteViewController alloc] init];
            PMRIVC.isPerson = YES;
            PMRIVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRIVC animated:YES];
        } break;
        case MineHeaderViewTapTypeOfAttention: {
            NSLog(@"收藏关注");
            PMineCollectViewController *PMCVC = [[PMineCollectViewController alloc] init];
            PMCVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMCVC animated:YES];
        } break;
        default:
            break;
    }
}
- (MineHeaderView *)tableViewHeaderView {
    if (!_tableViewHeaderView) {
        _tableViewHeaderView = [[MineHeaderView alloc] initWithTarget:self roleType:IDTypeOfWorker];
        _tableViewHeaderView.userInteractionEnabled = YES;
        _tableViewHeaderView.backgroundColor = COLOR_OF_WHITE;
    }
    return _tableViewHeaderView;
}
- (void)loadDataBaseData {
    __weak __typeof(self)weakSelf = self;
    [DataToolsControl getMyBaseInfoForWorker:^(BOOL requestFlag) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (requestFlag) {
            [strongSelf.tableViewHeaderView setWorkerPartBaseInfo];
        }
    }];
}

@end
